########################################
### R Function: fsQCA.anchor.ahn.lee ###
########################################

fsQCA.anchor.ahn.lee=function(raw.data, depvar, indepvars, n.cut, reps, explain, error.reps, anchors, user.thresholds, given.incl.cut0, given.incl.cut1, min, devs){
  
  fun.threshgen=function(anchors, user.thresholds, d){
    user.thresholds[anchors,]=user.thresholds[anchors,]*runif(n=ncol(user.thresholds), min=1-d, max=1+d)
    out=user.thresholds
    return(out)
  }
  
  fun.error=function(x){
    out=as.data.frame(fsQCA.sim.inclcut(dataset=x, depvar=depvar, indepvars=indepvars, n.cut=n.cut, reps=reps, explain=explain, min=min))
    return(out)
  }
  
  for(i in devs){
    anchor.permutations=rlply(.n=error.reps, .expr=fun.threshgen(anchors, user.thresholds=user.thresholds, d=i))
    datasets=lapply(X=anchor.permutations, calibrate.ahn.lee)
    out=lapply(X=datasets, FUN=fun.error)
    results=rbind.fill(out)
    Configurations=do.call(paste, as.data.frame(results[,4:ncol(results)], stringsAsFactors=FALSE))
    Configurations=gsub(pattern=" NA", replacement="", x=Configurations)
    Configurations=gsub(pattern=" ", replacement=" + \n  ", x=Configurations)
    results=cbind(results[,1:3], paste("Measurement Error = ", i, sep=""), Configurations)
    colnames(results)[4]="error"
    results$incl.cut1.val=as.numeric(as.vector(results$incl.cut1.val))
    results$incl.cut0.val=as.numeric(as.vector(results$incl.cut0.val)) 
    assign(paste("xxxxx.error", i, sep="."), results)
  }
  
  results=lapply(ls(pattern="xxxxx.error"), function(x) get(x))
  results=rbind.fill(results) 
  
  plot=ggplot(data=results, aes(x=incl.cut0.val, y=incl.cut1.val, colour=Configurations))+geom_point()+scale_color_hue(c=150, l=60)+xlim(0,1)+ylim(0,1)+xlab(label="Maximum Sufficiency Inclusion Score")+ylab(label="Minimum Sufficiency Inclusion Score")+geom_point(x=given.incl.cut0, y=given.incl.cut1, shape=17, color="black", size=2)+guides(col=guide_legend(keyheight=2))+facet_wrap(~error, ncol=2)
  
  return(list("results"=results, "plot"=plot))  
  
}